import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Rectangle;
import flash.geom.Point;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.display.Sprite;
import flash.ui.Keyboard;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import flash.filters.GlowFilter;
import haxe.FastList; 
import flash.display.Shape;
import flash.events.MouseEvent;
import flash.events.EventDispatcher;
import flash.events.Event;
import TextArea;
import PauseMenu;
import FadingText;
import CustomSprite;
import GenericMenu;

import PopUp;
import PopUpText;

import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.net.SharedObject;
import haxe.remoting.AMFConnection;

//import haxe.Timer;

import HelperMethods;

import Images;  
import Blob;
import Sounds;
import Button;
import KidnapList;
import Kongregate;



class Scene extends CustomSprite 
{
  public var Speed : Float;
  public var PrincessPosition:Array<Array<Bool>>;
  public var Player : CharacterStat;
  public var currentBackground : CustomSprite;
  private var BackButton:Sprite;
  public var MenuBar:CustomSprite;
  public var KidnapPrincess : CustomSprite;
  public var ActionButton : CustomSprite;
  public var ActionMenuItem : ActionMenu;
  public var ResourceButton : CustomSprite;
  public var ResourceMenuItem : ResourceMenu;
  public var LeftButton : CustomSprite;
  public var SpeedText : TextField;
  public var RightButton : CustomSprite;

  public var SuspicionBar:CustomSprite;
  public var SuspicionBarText:TextField;
  public var SuspicionBarInner:CustomSprite;
  public var SuspicionBarOuter:CustomSprite;
  public var SuspicionText:TextField;
  public var FearBar:CustomSprite;
  public var FearBarText:TextField;
  public var FearText:TextField;
  public var FearBarInner:CustomSprite;
  public var FearBarOuter:CustomSprite;
  public var PopulationText:TextField;
  public var PrincessStatus:CustomSprite;

public var PrincessStatusImage1:CustomSprite;
public var PrincessStatusImage2:CustomSprite;
public var PrincessStatusImage3:CustomSprite;
public var PrincessStatusImage4:CustomSprite;
public var PrincessStatusImage5:CustomSprite;
public var PrincessStatusImage6:CustomSprite;
public var PrincessStatusCurrentImage:String;
  public var CurrentMenu:String;


  public var Castle:CustomSprite;


  public var OkPopUp : PopUp;
  public var OkPopUpText : PopUpText;
  private var ignoreKeyPress : String;
  

  public var text : String;
  var mKeyDown:Array<Bool>;
  var lastUp:Int;
  var Pause:String;
  public var volume:Bool;
  public var sound:Bool;
  public var running:Bool;
  public var victory:String;
  public var TurnLeft:TextField;

    private var  myTimer:Timer;
    private static inline var FRAME_RATE:Int = 40;
    private var _period:Float;
    private var _beforeTime:Int;
    private var _afterTime:Int;
    private var _timeDiff:Int;
    private var _sleepTime:Int;
    private var _overSleepTime:Int;
    private var _excess:Int;

  var State:String;
  var PauseTillKeyPressed:Bool;
  public var Intro:CustomSprite;
  public var IntroText:TextField;
  public var IntroOK:CustomSprite;

  public var Loss:CustomSprite;
  public var LossText:TextField;
  public var LossQuit:CustomSprite;
  public var LossRetry:CustomSprite;

  public var Win:CustomSprite;
  public var WinText:TextField;
  public var WinQuit:CustomSprite;
  public var WinContinue:CustomSprite;

  public var pauseMenu:PauseMenu;
  var pauseMenuPoint:Point;
  public var saveGame:Int;
  //public var savedData:flash.net.SharedObject;
  private var player:SoundPlayer;
  var kongVar : CKongregate;

  public function new(inBackground:BitmapData)
  {
  //Need to RegisterMethods inOrder to Save
  haxe.remoting.AMFConnection.registerClassAlias("CharacterStatAlias",CharacterStat);
  haxe.remoting.AMFConnection.registerClassAlias("KidnapingAlias",Kidnaping); 
  haxe.remoting.AMFConnection.registerClassAlias("KidnapListAlias",KidnapList);
  haxe.remoting.AMFConnection.registerClassAlias("CustomSpriteAlias",CustomSprite); 
  haxe.remoting.AMFConnection.registerClassAlias("HeroAlias",  Hero);

  super();
   //
  try
  {
  kongVar = new CKongregate();
  }
  catch (msg:Dynamic)
  {
  }
   Speed = 1;
    saveGame = 0;
   PrincessStatusCurrentImage = "";
   PrincessPosition = [[]];

 //old determine what to use
  pauseMenu = new PauseMenu();
  pauseMenuPoint = new Point(0,370);

  running = false;
  victory = "None";
  Pause = "UnPaused";
  volume = true;
  sound = true;

  State = "Wait"; 
  
  ignoreKeyPress = "";
  PauseTillKeyPressed = false;
  currentBackground = new CustomSprite();
  currentBackground.graphics.beginBitmapFill(inBackground.clone());
  currentBackground.graphics.drawRect(0, 0, inBackground.width,inBackground.height);
  currentBackground.graphics.endFill();
  currentBackground.resize(Constants.flashWidth,Constants.flashHeight);

  var grass= new CustomSprite();
  grass.graphics.beginBitmapFill(new Grass());
  grass.graphics.drawRect(10, 10, 780,580);
  grass.graphics.endFill();
  currentBackground.addChild(grass);

  MenuBar = new CustomSprite();
  MenuBar.graphics.beginFill(0xFFFFFF);
  MenuBar.graphics.drawRect(0,0,780,75);
  MenuBar.graphics.endFill();
  MenuBar.x=10; MenuBar.y=10;

  KidnapPrincess = new CustomSprite();
  KidnapPrincess.graphics.beginBitmapFill(inBackground.clone());
  KidnapPrincess.graphics.drawRect(0, 0, inBackground.width,inBackground.height);
  KidnapPrincess.resize(50,50);
  KidnapPrincess.buttonMode = true;
  KidnapPrincess.x = 240; KidnapPrincess.y = 20;

  ActionButton  = new CustomSprite();
  ActionButton.graphics.beginBitmapFill(new Bombs());
  ActionButton.graphics.drawRect(0, 0, 100,100);
  ActionButton.resize(50,50);
  ActionButton.isHover = true;
  ActionButton.setHoverText( "<font='14'><b>Command<b></font>");
  ActionButton.buttonMode = true;
  ActionButton.x = 300; ActionButton.y = 20;

  ResourceButton = new CustomSprite();
//   ResourceButton.graphics.beginBitmapFill(inBackground.clone());
//   ResourceButton.graphics.drawRect(0, 0, inBackground.width,inBackground.height);
//   ResourceButton.resize(51,51);
  ResourceButton.graphics.beginBitmapFill(new ResourceImage());
  ResourceButton.graphics.drawRect(0, 0, 50,50);
  ResourceButton.isHover = true;
  ResourceButton.setHoverText( "<font='14'><b>Resources<b></font>");
  ResourceButton.buttonMode = true;
  ResourceButton.x = 230; ResourceButton.y = 20;


  SuspicionBar = new CustomSprite();
  SuspicionBarText = new TextField();
  SuspicionBarText.htmlText = "Suspicion: ";
  SuspicionBar.addChild(SuspicionBarText);
  SuspicionBarText.y = -5;
  SuspicionBarOuter = new CustomSprite();
  SuspicionBarOuter.graphics.beginFill(0x000000);
  SuspicionBarOuter.graphics.drawRect(0,0,100,10);
  SuspicionBarOuter.graphics.endFill();
  SuspicionBar.addChild(SuspicionBarOuter);
  SuspicionBarOuter.x = 60;

  SuspicionBarInner = new CustomSprite();
  SuspicionBarInner.graphics.beginFill(0x0000FF);
  SuspicionBarInner.graphics.drawRect(1,1,0,8);
  SuspicionBarInner.graphics.endFill();
  SuspicionBar.addChild(SuspicionBarInner);
  SuspicionBarInner.x = 60;

  SuspicionBar.x = 600; SuspicionBar.y =40;
  
//   public var FearBar:CustomSprite;
//   public var FearBarText:TextField;
//   public var FearBarInner:CustomSprite;
//   public var FearBarOuter:CustomSprite;

  FearBar = new CustomSprite();
  FearBarText = new TextField();
  FearBarText.htmlText = "Fear: ";
  FearBar.addChild(FearBarText);
  FearBarText.y = -5;
  FearBarOuter = new CustomSprite();
  FearBarOuter.graphics.beginFill(0x000000);
  FearBarOuter.graphics.drawRect(0,0,100,10);
  FearBarOuter.graphics.endFill();
  FearBar.addChild(FearBarOuter);
  FearBarOuter.x = 60;

  FearBarInner = new CustomSprite();
  FearBarInner.graphics.beginFill(0xFF0000);
  FearBarInner.graphics.drawRect(1,1,0,8);
  FearBarInner.graphics.endFill();
  FearBar.addChild(FearBarInner);
  FearBarInner.x = 60;

  FearBar.x = 600; FearBar.y =60;

  OkPopUp = new PopUp(inBackground.clone(),"Test Message");
  OkPopUpText = new PopUpText(inBackground.clone(),"Test Message");
  mKeyDown = [];
  lastUp = Keyboard.RIGHT;
  
  TurnLeft = new TextField();

  Player = new CharacterStat(); 
  Player.Money = 0;
  Player.addEventListener("updateValues",updateValues);

  LeftButton = new CustomSprite();
  LeftButton.graphics.beginBitmapFill(new LeftArrow());
  LeftButton.graphics.drawRect(0, 0, 30,50);
  LeftButton.x = 420;LeftButton.y =20;
  LeftButton.buttonMode = true;

  SpeedText = new TextField();

  RightButton = new CustomSprite();
  RightButton.graphics.beginBitmapFill(new RightArrow());
  RightButton.graphics.drawRect(20, 0, 30,50);
  RightButton.x = 480;RightButton.y =20;
  RightButton.buttonMode = true;
  


  Castle = new CustomSprite();
  Castle.graphics.beginBitmapFill(new CastleImage());
  Castle.graphics.drawRect(0, 0, 530,500);
//   Castle.graphics.beginFill(0xFFFFFF);
//   Castle.graphics.lineStyle(1);
//   Castle.graphics.drawRect(0,0,530,500);
  Castle.graphics.endFill();
  Castle.x = 150;Castle.y= 100;

  addChild(currentBackground);
  addChild(Castle);
  addChild(MenuBar);
  addChild(SuspicionBar);
  addChild(FearBar);
  //addChild(KidnapPrincess);

  addChild(ResourceButton);
  addChild(ActionButton);
  addChild(LeftButton);
  addChild(RightButton);
  
  LeftButton.addEventListener(MouseEvent.CLICK, onLeftArrowButtonClick);
  RightButton.addEventListener(MouseEvent.CLICK, onRightArrowButtonClick);
  ResourceButton.addEventListener(MouseEvent.CLICK, onResourceButtonClick);
  ActionButton.addEventListener(MouseEvent.CLICK, onActionButtonClick);

  addChild(SpeedText);
  SpeedText.x = 425;
  SpeedText.autoSize = TextFieldAutoSize.CENTER;
  SpeedText.y = 20;
  SpeedText.htmlText = "<Font size = '15'><u>Speed</u>\n  "+ Speed + "</font>";
  SpeedText.selectable = false;
  PopulationText = new TextField();
  addChild(PopulationText);
  PopulationText.x = 600;
  PopulationText.autoSize = TextFieldAutoSize.LEFT;
  PopulationText.y = 10;
  var Population = 1000 * Math.pow(10,Player.PopulationLevel);
  var suffix = "";
  if(Player.PopulationLevel >= 6)
  {
    Population = 1 * Math.pow(10,Player.PopulationLevel-6);
    suffix = " Mil";
  }
  PopulationText.htmlText = "Population: " + HelperMethods.format(Population,0) + suffix;

  FearText = new TextField();
  addChild(FearText);
  FearText.x = 660;
  FearText.autoSize = TextFieldAutoSize.RIGHT;
  FearText.y = 56;
  FearText.htmlText = "<font color='#FFFFFF' size='10'>"+Player.Fear+"</font>";

  SuspicionText= new TextField();
  addChild(SuspicionText);
  SuspicionText.x = 660;
  SuspicionText.autoSize = TextFieldAutoSize.RIGHT;
  SuspicionText.y = 36;
  SuspicionText.htmlText = "<font color='#FFFFFF' size='10'>"+Player.Suspicion+"</font>";

  addChild(TurnLeft);
  TurnLeft.x = 540;
  TurnLeft.y = 40; 


  PrincessStatus = new CustomSprite();
  PrincessStatus.graphics.beginFill(0xFFFFFF);
  PrincessStatus.graphics.lineStyle(1);
  PrincessStatus.graphics.drawRect(0,0,75,75);
  PrincessStatus.x =10;PrincessStatus.y=10;
  addChild(PrincessStatus);

  PrincessStatusImage1 = new CustomSprite();
  PrincessStatusImage1.graphics.beginBitmapFill(new PrincessStatus1());
  PrincessStatusImage1.graphics.drawRect(0, 0, 75,75);
  PrincessStatusImage1.graphics.endFill();

  PrincessStatusImage2 = new CustomSprite();
  PrincessStatusImage2.graphics.beginBitmapFill(new PrincessStatus2());
  PrincessStatusImage2.graphics.drawRect(0, 0, 75,75);
  PrincessStatusImage2.graphics.endFill();

  PrincessStatusImage3 = new CustomSprite();
  PrincessStatusImage3.graphics.beginBitmapFill(new PrincessStatus3());
  PrincessStatusImage3.graphics.drawRect(0, 0, 75,75);
  PrincessStatusImage3.graphics.endFill();

  PrincessStatusImage4 = new CustomSprite();
  PrincessStatusImage4.graphics.beginBitmapFill(new PrincessStatus4());
  PrincessStatusImage4.graphics.drawRect(0, 0, 75,75);
  PrincessStatusImage4.graphics.endFill();

  PrincessStatusImage5 = new CustomSprite();
  PrincessStatusImage5.graphics.beginBitmapFill(new PrincessStatus5());
  PrincessStatusImage5.graphics.drawRect(0, 0, 75,75);
  PrincessStatusImage5.graphics.endFill();

  PrincessStatusImage6 = new CustomSprite();
  PrincessStatusImage6.graphics.beginBitmapFill(new PrincessStatus6());
  PrincessStatusImage6.graphics.drawRect(0, 0, 75,75);
  PrincessStatusImage6.graphics.endFill();

  Intro = new CustomSprite();
  Intro.graphics.beginFill(0xFFFFFF);
  Intro.graphics.lineStyle(1);
  Intro.graphics.drawRect(0,0,400,400);
  Intro.x =200;Intro.y=150;
  Intro.graphics.endFill();

  IntroText = new TextField();
  IntroText.width = 400;
  IntroText.htmlText = "<font size='20'><b><u>Welcome</u></b>\nYou're responsible for a small kingdom, but your ambitions aren't satisfied with that. You want so much more.   Of course, since its your kingdom is blessed with peace, there is no need to wage war with neighboring kingdoms. Until you come up with your own threat.  You must constantly stage kidnapping, until you take over the world.  But be careful, it's only a matter time before people figure out your plan.</font>";
  IntroText.autoSize = TextFieldAutoSize.CENTER;
  IntroText.wordWrap = true;
  IntroText.selectable = false;
  Intro.addChild(IntroText);
  IntroOK = new Button(200,50,"Start Already!");
  IntroOK.addEventListener(MouseEvent.CLICK, onIntroOKClick);
  IntroOK.y = 300;IntroOK.x = 100;
  Intro.addChild(IntroOK);


  Loss= new CustomSprite();
  Loss.graphics.beginFill(0xFFFFFF);
  Loss.graphics.lineStyle(1);
  Loss.graphics.drawRect(0,0,400,400);
  Loss.x =200;Loss.y=150;
  Loss.graphics.endFill();

  LossText = new TextField();
  LossText.width = 400;
  LossText.htmlText = "<font size='20'><b><u>Too bad.</u></b>\nYou're kingdom got too suspicious and staged a coup d'etat.  Looks like you've been sentenced to the guillotine, with no chance of appeal.</font>";
  LossText.autoSize = TextFieldAutoSize.CENTER;
  LossText.wordWrap = true;
  LossText.selectable = false;
  Loss.addChild(LossText);
  LossRetry = new Button(200,50,"Retry");
  LossRetry.addEventListener(MouseEvent.CLICK, onLossRetryClick);
  LossRetry.y = 200;LossRetry.x = 100;
  Loss.addChild(LossRetry);
  LossQuit = new Button(200,50,"Quit");
  LossQuit.addEventListener(MouseEvent.CLICK, onLossQuitClick);
  LossQuit.y = 300;LossQuit.x = 100;
  Loss.addChild(LossQuit);


  Win= new CustomSprite();
  Win.graphics.beginFill(0xFFFFFF);
  Win.graphics.lineStyle(1);
  Win.graphics.drawRect(0,0,400,400);
  Win.x =200;Win.y=150;
  Win.graphics.endFill();

  WinText = new TextField();
  WinText.width = 400;
  WinText.htmlText = "<font size='20'><b><u>Hooray!</u></b>\nYou've Suppressed the Entire World!  Not bad for an innocent looking princess.  But think you can keep going? See how you'd do with a larger population.</font>";
  WinText.autoSize = TextFieldAutoSize.CENTER;
  WinText.wordWrap = true;
  WinText.selectable = false;
  Win.addChild(WinText);
  WinContinue = new Button(200,50,"Continue");
  WinContinue.addEventListener(MouseEvent.CLICK, onWinContinueClick);
  WinContinue.y = 200;WinContinue.x = 100;
  Win.addChild(WinContinue);
  WinQuit = new Button(200,50,"Quit");
  WinQuit.addEventListener(MouseEvent.CLICK, onWinQuitClick);
  WinQuit.y = 300;WinQuit.x = 100;
  Win.addChild(WinQuit);
  CurrentMenu = "";
  pauseMenu.addEventListener("Quit",onQuit);
  pauseMenu.addEventListener("Save",onSave);
  
  }
  public function onQuit(event:Event)
  {
    removeChild(pauseMenu);
    //this.removeEventListener(Event.ENTER_FRAME, OnEnter);
    State = "EndGame";
    dispatchEvent(new Event("LevelQuit"));
  }
  public function onSave(event:Event)
  {
      var savedData = SharedObject.getLocal("GameData");
      savedData.data.Player = Player;
      savedData.data.PrincessPosition = PrincessPosition;
      savedData.flush();
  }
public function PurchasePrincess(event:Event)
{
Player.PrincessTotal+=1;

Player.Fear -=10;
}

//Load Level, so that it isn't automatically loaded automatically.
public function Load(inVolume:Bool,inSound:Bool,inContinue:Bool)
{
  CurrentMenu = "";
  volume = inVolume;
  sound = inSound;
  running = true;
  flash.Lib.current.addChild(this);
 
   //addhild(OkPopUp);
  
  //OkPopUpText.Load();
  //this.addEventListener(Event.ENTER_FRAME, OnEnter)
  //On Enter Was very slow on my computer. So I'm using the timer event so it doesn't render as much.
  myTimer = new Timer(20);
  myTimer.addEventListener("timer", timerHandler);
  myTimer.start();
  stage.addEventListener(KeyboardEvent.KEY_DOWN, OnKeyDown );
  stage.addEventListener(KeyboardEvent.KEY_UP, OnKeyUp );
  
  this.addEventListener("PopUpTextEvent",onPopUpTextEvent);
  if(!inContinue)
  {
      addChild(Intro);
      try
      {
	kongVar.SubmitStat("StartGame",1);
      }
      catch(msg: Dynamic) 
      {

      }
  }
  
  State = "Intro";
  if(inContinue)
  {
      try
      {
	kongVar.SubmitStat("ContinueGame",1);
      }
      catch(msg: Dynamic) 
      {

      }
    try
    {
      var savedData = SharedObject.getLocal("GameData");
      if(savedData.data.Player != null)
      {
	Player = savedData.data.Player;
	PrincessPosition = savedData.data.PrincessPosition;
      }
    State = "Playing";
    }
    catch(err:Dynamic)
    {trace(err);}
  }

  for(Kidnap in Player.Kidnapings)
  {
    Kidnap.draw();
    if(Kidnap.addedPrincess)
      {currentBackground.addChild(Kidnap.PrincessAvatar);}
    if(Kidnap.addedVillian)
      {currentBackground.addChild(Kidnap.VillianAvatar);}
    if(Kidnap.addedHero)
      {currentBackground.addChild(Kidnap.HeroAvatar);}
  }
  player = new SoundPlayer(Player.PopulationLevel+1);
  ResourceMenuItem = new ResourceMenu(new Background(),Player);
  ResourceMenuItem.x = 100;
  ActionMenuItem = new ActionMenu(new Background(),Player);
  ActionMenuItem.x = 100;
  ActionMenuItem.addEventListener("ExpandedCastle",onExpandedCastle);
  GetPrincessStatusImage();
}

private function isPaused():Bool{
      if(Pause != "UnPaused")
      {
	if(Pause == "Paused" || Pause == "Pausing")
          {
          addPauseMenu();
          }
        else if(Pause == "UnPausing")
         {
          removePauseMenu();
          }
         return true;
      }
      return false;
}

public function drawScreen()
{
  SuspicionBar.removeChild(SuspicionBarInner);
  SuspicionBarInner.graphics.clear();
  SuspicionBarInner.graphics.beginFill(0x0000FF);
  SuspicionBarInner.graphics.drawRect(1,1,98*(Player.Suspicion/10000),8);
  SuspicionBarInner.graphics.endFill();
  SuspicionBar.addChild(SuspicionBarInner);


  FearBar.removeChild(FearBarInner);
  FearBarInner.graphics.clear();
  FearBarInner.graphics.beginFill(0xFF0000);
  FearBarInner.graphics.drawRect(1,1,98*(Player.Fear/Player.MaxFear),8);
  FearBarInner.graphics.endFill();
  FearBar.addChild(FearBarInner);

  var Population = 1000 * Math.pow(10,Player.PopulationLevel);
  var suffix = "";
  if(Player.PopulationLevel >= 6)
  {
    Population = 1 * Math.pow(10,Player.PopulationLevel-6);
    suffix = " Billion";
  }
  PopulationText.htmlText = "Population: " + HelperMethods.format(Population,0) + suffix;
  FearText.htmlText = "<font color='#FFFFFF' size='10'>"+Player.Fear+"</font>";
  SuspicionText.htmlText = "<font color='#FFFFFF' size='10'>"+Math.round(Player.Suspicion)+"</font>";
  ActionMenuItem.ExpandCastle.setHoverText("<u>Level " + (Player.PopulationLevel+1) + " - " + 5000 * Math.pow(2,Player.PopulationLevel) + "</u>\n"+"With enough fear, you'll be able to mobilize your army to expand your empire.");
  ActionMenuItem.Propaganda.setHoverText("<u>Level " + (Player.Propaganda+1) + " - " + 1000 * Math.pow(2,Player.Propaganda) + "</u>\n" + "Nothing like acquiring some newpaper and schools, to educate the public properly. Decrease Suspicion a small percent each turn.");
  SpeedText.htmlText = "<Font size = '15'><u>Speed</u>\n  "+ Speed + "</font>";
  ResourceMenuItem.PurchasePrincessText.htmlText = ResourceMenuItem.getPurchasePrincessText();
}

public function GetPrincessStatusImage()
{
  if(Player.PopulationLevel <= 0)
  {
    if(PrincessStatusCurrentImage != "1")
    {
      while(PrincessStatus.numChildren != 0)
      {
	PrincessStatus.removeChildAt(0);
      }
      PrincessStatus.addChild(PrincessStatusImage1);
      PrincessStatusCurrentImage = "1";
    }
    
  }
  else if(Player.PopulationLevel == 1)
  {
    if(PrincessStatusCurrentImage != "2")
    {
      while(PrincessStatus.numChildren != 0)
      {
	PrincessStatus.removeChildAt(0);
      }
      PrincessStatus.addChild(PrincessStatusImage2);
      PrincessStatusCurrentImage = "2";
    }
    
  }
  else if(Player.PopulationLevel == 2)
  {
    if(PrincessStatusCurrentImage != "3")
    {
      while(PrincessStatus.numChildren != 0)
      {
	PrincessStatus.removeChildAt(0);
      }
      PrincessStatus.addChild(PrincessStatusImage3);
      PrincessStatusCurrentImage = "3";
    }
    
  }
  else if(Player.PopulationLevel == 3)
  {
    if(PrincessStatusCurrentImage != "4")
    {
      while(PrincessStatus.numChildren != 0)
      {
	PrincessStatus.removeChildAt(0);
      }
      PrincessStatus.addChild(PrincessStatusImage4);
      PrincessStatusCurrentImage = "4";
    }
    
  }
  else if(Player.PopulationLevel == 4)
  {
    if(PrincessStatusCurrentImage != "5")
    {
      while(PrincessStatus.numChildren != 0)
      {
	PrincessStatus.removeChildAt(0);
      }
      PrincessStatus.addChild(PrincessStatusImage5);
      PrincessStatusCurrentImage = "5";
    }
    
  }
  else if(Player.PopulationLevel >= 5)
  {
    if(PrincessStatusCurrentImage != "6")
    {
      while(PrincessStatus.numChildren != 0)
      {
	PrincessStatus.removeChildAt(0);
      }
      PrincessStatus.addChild(PrincessStatusImage6);
      PrincessStatusCurrentImage = "6";
    }
    
  }
}

private function StartKidnapPrincess()
{
  if(Player.PrincessTotal > Player.PrincessUsed)
  {
    Player.PrincessUsed++;
    var kidnap = new Kidnaping();
    kidnap.HasPrincess = true;
    kidnap.currentState = "addPrincess";
    kidnap.FramesLeft = Player.KidnapTime;
    Player.Kidnapings.add(kidnap);
  }
}

private function onExpandedCastle(event:Event)
{
  try
  {
    kongVar.SubmitStat("LevelBeaten",Player.PopulationLevel+1);
  }
  catch(msg: Dynamic) 
  {

  }
  player.increaseState();
  GetPrincessStatusImage();
  
  if(Player.PopulationLevel == 5)
  {
    addChild(Win);
    State = "Won";
  }
}
private function onLeftArrowButtonClick(event:MouseEvent) {
    DecreaseSpeed();
}
private function onRightArrowButtonClick(event:MouseEvent) {
    IncreaseSpeed();
}
private function onIntroOKClick(event:MouseEvent) {
    removeChild(Intro);
    State = "Playing";
}
private function onLossRetryClick(event:MouseEvent) {
    removeChild(Loss);
    dispatchEvent(new Event("LevelRetry"));

}
private function onLossQuitClick(event:MouseEvent) {
    removeChild(Loss);
    State = "EndGame";
    dispatchEvent(new Event("LevelQuit"));
}

private function onWinContinueClick(event:MouseEvent) {
    removeChild(Win);
    State="Playing";
}
private function onWinQuitClick(event:MouseEvent) {
    removeChild(Win);
    State = "EndGame";
    dispatchEvent(new Event("LevelQuit"));
}

public function DecreaseSpeed()
{
  var decreaseAmount = 0.5 * Speed;
  if(decreaseAmount >= 0.25)
    {Speed = decreaseAmount;}
}
public function IncreaseSpeed()
{
  var increaseAmount = 2 * Speed;
  if(increaseAmount <= 4)
    {Speed = increaseAmount;}
}
private function onResourceButtonClick(event:MouseEvent) {
  if(State!= "Playing"){return;}
  if(CurrentMenu == "Action")
  {
      ActionMenuItem.removeEventListener("Back",onActionMenuItemBack);
      removeChild(ActionMenuItem);
  }	
  CurrentMenu = "Resource";
  addChild(ResourceMenuItem);
  ResourceMenuItem.addEventListener("Back",onResourceMenuItemBack);
}
private function onResourceMenuItemBack(event:GenericMenuEvent){
  ResourceMenuItem.removeEventListener("Back",onResourceMenuItemBack);
  removeChild(ResourceMenuItem);
  CurrentMenu = "";
}

private function onActionButtonClick(event:MouseEvent) {	
  if(State!= "Playing"){return;}
  if(CurrentMenu == "Resource")
  {
    ResourceMenuItem.removeEventListener("Back",onResourceMenuItemBack);
    removeChild(ResourceMenuItem);
  }
  CurrentMenu = "Action";
  addChild(ActionMenuItem);
  ActionMenuItem.addEventListener("Back",onActionMenuItemBack);
}
private function onActionMenuItemBack(event:GenericMenuEvent){
  ActionMenuItem.removeEventListener("Back",onActionMenuItemBack);
  removeChild(ActionMenuItem);
  CurrentMenu = "";
}
public function checkLose()
{
  if(Player.Suspicion >= 10000)
  {
    State="Loss";
  }
}
public function timerHandler(event:TimerEvent) {
      if(!volume)
      {
	 //pausePosition = player.getPosition();
         player.stop();
         
      }
      else
      {
        player.play(0);
      }
    if(State == "Wait")
    {
    }
    if(State == "Loss")
    {
      addChild(Loss);
    }
    else if(State == "Playing")
    {
      if(isPaused())
        {return;}
      //Player.Money += (Player.TaxRate*Player.Population)/1000;
      try
      {
	incrementPhase();
      }
      catch(msg:Dynamic)
      {
      trace(msg);
      }

      drawScreen();
      checkLose();
    }
      _afterTime = flash.Lib.getTimer();
       _timeDiff = _afterTime - _beforeTime;
       _sleepTime = (Std.int(_period) - _timeDiff) - _overSleepTime;
      if(_sleepTime <= 0) {
	_excess -= Std.int(_sleepTime);
	_sleepTime = 2;
      }
      myTimer.reset();
      myTimer.delay = _sleepTime;
      myTimer.start();
      event.updateAfterEvent;

    if(State == "EndGame")
    {
    //Show score
    //unLoad();
    }
}

public function incrementPhase()
{

StartKidnapPrincess();

Player.Suspicion += (Player.getSuspicionPerTurn())*Speed;
var stopPostion = 50;
for(Kidnap in Player.Kidnapings)
    {
      if(Kidnap.FramesLeft <= 0)
      {
	Player.Kidnapings.remove(Kidnap);
	Player.PrincessUsed--;
	Player.VillianUsed--;
	Player.HeroUsed--;
      }
      else
      {
	if(Kidnap.currentState == "addPrincess")
	{
	  var found = false;
	  for(xPos in 0...4)
	  {

	    for(yPos in 0...14)
	    {
	      try
	      {
	      if(PrincessPosition[xPos] == null)
		 {PrincessPosition[xPos] = [];}
	      if(PrincessPosition[xPos][yPos] == false)
		{
		  PrincessPosition[xPos][yPos] = true;
		  Kidnap.PostionX = xPos;
		  Kidnap.PostionY = yPos;
		  found = true;
		  break;
		}
	      }
	      catch (msg:Dynamic)
	      {trace(msg);}
	    }
	    if(found){break;}
	  }

	  if(!found)
	  {
	    Kidnap.addAvatars = false;
	    Kidnap.PostionX = 5;
	    Kidnap.PostionY = 0;
	  }
	  Kidnap.PrincessAvatar.y = 125+Kidnap.PostionY*30;
	  Kidnap.PrincessAvatar.x = 100-Kidnap.PostionX*30;
	  if(Kidnap.addAvatars)
	  {
	    try
	    {
	     currentBackground.addChild(Kidnap.PrincessAvatar);
	     Kidnap.addedPrincess = true;
	    }
	    catch(ex:Dynamic)
	    {
	    }
	  }
	  Kidnap.currentState = "addVillian";
	}

	try
	{
	if(Kidnap.HasPrincess && !Kidnap.HasVillian)
	{
	  if(Player.VillianTotal > Player.VillianUsed)
	  {
	      Player.VillianUsed++;
	      Kidnap.HasVillian = true;
	      Player.Fear += (10 * (Player.WriterTotal+1));
	  }
	}

	if(Kidnap.HasPrincess && Kidnap.HasVillian && !Kidnap.HasHero)
	{
	  if(Player.HeroTotal > Player.HeroUsed)
	  {
	      Player.HeroUsed++;
	      Kidnap.HasHero = true;
	  }
	}
	}
	catch (msg:Dynamic)
	{trace(msg);}


	try
	{
	if(Kidnap.HasPrincess && Kidnap.HasVillian)
	{
	  if(Kidnap.currentState == "addVillian")
	  {
	 // trace("add Villian");
	    Kidnap.VillianAvatar.x=-35;Kidnap.VillianAvatar.y=Kidnap.PrincessAvatar.y-20;
	    if(Kidnap.addAvatars)
	    {
	      try
	      {
	      currentBackground.addChild(Kidnap.VillianAvatar);
	      Kidnap.addedVillian = true;
	      }
	      catch(ex:Dynamic)
	      {
	      }
	    }
	   // trace("PRincess");
	    Kidnap.currentState = "getPrincess";

	  }
	  if(Kidnap.currentState == "getPrincess")
	  {
	   Kidnap.VillianAvatar.x += 3*Speed;
	   if(Kidnap.VillianAvatar.x >= Kidnap.PrincessAvatar.x-15)
	   {
	      Kidnap.currentState = "exit";
	      Kidnap.HeroAvatar.x = Kidnap.PrincessAvatar.x; Kidnap.HeroAvatar.y = 550;
	      if(Kidnap.addAvatars)
	      {
		try
		{
		currentBackground.addChild(Kidnap.HeroAvatar);
		Kidnap.addedHero = true;
		}
		catch(ex:Dynamic)
		{
		}
	      }
	   }
	  }
	  if(Kidnap.currentState == "exit")
	  {
	   Kidnap.PrincessAvatar.y -= 10*Speed;
	   Kidnap.VillianAvatar.y -= 10*Speed;
	   if(Kidnap.PrincessAvatar.y <= stopPostion)
	   {
	    if(Kidnap.addAvatars)
	    {
	      try
	      {
	      currentBackground.removeChild(Kidnap.PrincessAvatar);
	      currentBackground.removeChild(Kidnap.VillianAvatar);
	      Kidnap.addedPrincess = false;
	      Kidnap.addedVillian = false;
	      }
	      catch(ex:Dynamic)
	      {
	      }
	    }
	    if(Kidnap.PostionX < 5)
	    {
	      PrincessPosition[Kidnap.PostionX][Kidnap.PostionY] = false;
	    }
	    Kidnap.currentState = "HeroAdded";
	   }
	  }
	
	}
	}
	catch (msg:Dynamic)
	{trace(msg);}

	try
	{
	if(Kidnap.HasPrincess && Kidnap.HasVillian && Kidnap.HasHero)
	{
	  if(Kidnap.currentState == "HeroAdded")
	    {

	      Kidnap.currentState = "HeroExits";
	    }
	  if(Kidnap.currentState == "HeroExits")
	    {
	       Kidnap.HeroAvatar.y -= 10*Speed;
	       if(Kidnap.HeroAvatar.y < stopPostion)
	       {
		if(Kidnap.addAvatars)
		{
		  try
		  {
		  currentBackground.removeChild(Kidnap.HeroAvatar);
		  Kidnap.addedHero = false;
		  }
		  catch(ex:Dynamic)
		  {}
		}
		Kidnap.currentState = "Wait";
	       }
	      
	    }
	  if(Kidnap.currentState == "Wait")
	  {
	    Kidnap.FramesLeft -= 1*Speed;
	    if(Kidnap.FramesLeft< 0 )
	    {

	    }
	  }
	}
		}
	catch (msg:Dynamic)
	{trace(msg);}
      }

    }

}

public function updateValues(e:Event)
{
}


private function onPopUpTextEvent(event:PopUpTextEvent)
{
  removeChild(OkPopUpText);  
}

//Define Win
public function checkEnd() : Bool
{
  //End if won or if overthrown.
  return false;
}
//When we're done with the level, we'll unload in.
public function unLoad()
{
  running = false;
  //removeChild(new Bitmap(currentBackground));
  for(Kidnap in Player.Kidnapings)
  {
    if(Kidnap.addedPrincess)
      {currentBackground.removeChild(Kidnap.PrincessAvatar);}
    if(Kidnap.addedVillian)
      {currentBackground.removeChild(Kidnap.VillianAvatar);}
    if(Kidnap.addedHero)
      {currentBackground.removeChild(Kidnap.HeroAvatar);}
  }
      if(CurrentMenu == "Action")
      {
	  ActionMenuItem.removeEventListener("Back",onActionMenuItemBack);
	  removeChild(ActionMenuItem);
      }	
      if(CurrentMenu == "Resource")
      {
	ResourceMenuItem.removeEventListener("Back",onResourceMenuItemBack);
	removeChild(ResourceMenuItem);
      }
  //Player = new CharacterStat();
  player.stop();
  myTimer.stop();
  //Player = new CharacterStat();
  flash.Lib.current.removeChild(this);
}
public function OnKeyDown(event:KeyboardEvent)
   {
      // When a key is held down, multiple KeyDown events are generated.
      // This check means we only pick up the first one.
      if (!mKeyDown[event.keyCode])
      {
        if(ignoreKeyPress != "")
           {return;}

                  

         //Press any key to continue scence
         PauseTillKeyPressed = false;
         // Store for use in game
         mKeyDown[event.keyCode] = true;
        if(State == "Playing")
        {
//I do this here, because if they hold down P,
	 // it won't pause and unpause constantly.
	  if(mKeyDown[ 80 ] == true)
	  {
	      if(Pause == "Paused" || Pause == "Pausing")
                {
                  Pause = "UnPausing";
                }
              else 
                {
                  Pause = "Pausing";
		  pauseMenu.x = pauseMenuPoint.x;
		  pauseMenu.y = pauseMenuPoint.y;
		  addChild(pauseMenu);
                }
	  }
	  if(isPaused()){return;}


	}
// 	  if(mKeyDown[ 77 ] == true)
// 	  {
// 	      Mute = !Mute;
// 	  }
      }
    }
public function OnKeyUp (event:KeyboardEvent)
    {
      mKeyDown[event.keyCode] = false;
      lastUp = event.keyCode;
    }

//Pause Menu
public function addPauseMenu()
{
pauseMenu.x = pauseMenuPoint.x;
pauseMenu.y = pauseMenuPoint.y;
if(pauseMenuPoint.y <= 0)
{
Pause = "Paused";
} 
if(Pause == "Pausing")
{
 pauseMenuPoint.y = pauseMenuPoint.y - 20;
}
   
}
public function removePauseMenu()
{
  pauseMenu.x = pauseMenuPoint.x;
  pauseMenu.y = pauseMenuPoint.y;
  if(pauseMenuPoint.y >= 380)
  {
    Pause = "UnPaused";
    removeChild(pauseMenu);
  } 
  if(Pause == "UnPausing")
  {
    pauseMenuPoint.y = pauseMenuPoint.y + 20;
  }
}

}

